package com.supermarket.controller;


import com.supermarket.dto.AdminDto;
import com.supermarket.entity.Admin;
import com.supermarket.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("login")
    public Map login(AdminDto adminDto, HttpSession session){

        HashMap<String, Object> map = new HashMap<>();

        //判断
        if(adminDto!=null && adminDto.getUsername()!=null && adminDto.getPassword()!=null){
            //判断验证码
            if(session.getAttribute("code").toString().equals(adminDto.getCaptcha())){
                //通过前端输入的用户名和密码查询数据库
                Admin db_admin =  adminService.login(adminDto.getUsername(),adminDto.getPassword());
                //判断
                if(db_admin!=null){

                    //session.setMaxInactiveInterval(10000000);
                    //保存到session中
                    session.setAttribute("admin",db_admin);
                    //返回
                    map.put("code",200);
                    map.put("msg","success");
                    map.put("data",db_admin);

                }else{
                    map.put("code",-1);
                    map.put("msg","fail");
                }

            }else {
                map.put("code",-1);
                map.put("msg","fail");
            }

        }else {
            map.put("code",-1);
            map.put("msg","fail");
        }

        return map;
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //退出：1.删除session中保存的admin数据  2.跳转到登录页面
        //request.getSession().removeAttribute("admin");//删除session中保存的admin数据
        request.getSession().invalidate();//销毁session

        response.sendRedirect(request.getContextPath()+"/login.html");
    }
}
